package lbframework.classe;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

public class Conexao {

    private static int contBegin = 0;
    private static Connection con;
    private static String ip = "localhost";
    private static String ipSec = "";
    private static int porta = 5432;
    private static String dataBase = "lucas";
    private static String usuario = "postgres";
    private static String senha = "postgres";

    public static void abrirConexao(String i_ip, int i_porta, String i_database, String i_usuario, String i_senha) throws Exception {
        abrirConexao(i_ip, "", i_porta, i_database, i_usuario, i_senha);
    }

    public static void abrirConexao(String i_ip, String i_ipSec, int i_porta, String i_database, String i_usuario, String i_senha) throws Exception {
        Class.forName("org.postgresql.Driver");

        ip = i_ip;
        ipSec = i_ipSec;
        porta = i_porta;
        dataBase = i_database;
        usuario = i_usuario;
        senha = i_senha;

        try {
            con = DriverManager.getConnection("jdbc:postgresql://" + i_ip + ":" + i_porta + "/" + i_database, i_usuario, i_senha);

        } catch (Exception ex) {
            if (!ipSec.isEmpty()) {
                con = DriverManager.getConnection("jdbc:postgresql://" + i_ipSec + ":" + i_porta + "/" + i_database, i_usuario, i_senha);
            } else {
                throw ex;
            }
        }
    }

    public static Connection getConexao() {
        return con;
    }

    public static Statement createStatement() throws Exception {
        testarConexao();
        return con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    }

    public static void begin() throws Exception {
        if (contBegin == 0) {
            con.setAutoCommit(false);
        }

        contBegin++;
    }

    public static void commit() throws Exception {
        contBegin--;

        if (contBegin == 0) {
            con.commit();
            con.setAutoCommit(true);
        }
    }

    public static void rollback() throws Exception {
        contBegin = 0;

        con.rollback();
        con.setAutoCommit(true);
    }

    public static void close() throws Exception {
        con.close();
    }

    private static void testarConexao() throws Exception {
        Statement stm = null;

        try {
            stm = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

            stm.execute("SELECT 1");
            stm.close();

        } catch (Exception ex) {

            abrirConexao(ip, ipSec, porta, dataBase, usuario, senha);
        }
    }

    public static PreparedStatement prepareStatement(String i_sql) throws Exception {
        return con.prepareStatement(i_sql);
    }
}
